package com.lwei.ljpro;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;

@SpringBootApplication
@EnableCaching
@ServletComponentScan //启用filter
public class LjproApplication {

    private static Logger logger = LoggerFactory.getLogger("mainAction");

    public static void main(String[] args) {
        SpringApplication.run(LjproApplication.class, args);
        logger.info("------启动完成-------");
        try {
            logger.info("-------开始获取本机地址-------");
            InetAddress host = InetAddress.getLocalHost();
            String hostAddress = host.getHostAddress();
            String hostName = host.getHostName();
            logger.info("----当前主机ip地址为：" + hostAddress);
            logger.info("----当前主机地址名为：" + hostName);
            logger.info("-------获取本机地址完成-------");
            logger.info("------------当前 本机访问地址 http://127.0.0.1"+getLocalPort());
            logger.info("------------当前 局域网访问地址 http://"+ hostAddress + getLocalPort());
        } catch (UnknownHostException e) {
            logger.error("本机地址解析失败", e);
        }
    }


    /**
     * 获取当前机器的端口号
     */
    public static String getLocalPort() {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        try {
            Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
            String port = objectNames.iterator().next().getKeyProperty("port");

            return "80".equals(port) ? "" : ":"+port;
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
            return "";
        }
    }


}

